<template>
    <div>
        <el-dialog v-model="inShow" title="货代提单" width="55%" align-center>
            <el-form
                :model="inFormData"
                :rules="formRules"
                size="small"
                label-width="90px"
                label-suffix="："
                ref="form">
                <div style="margin-bottom: 8px">
                    <el-button size="small" type="primary" :loading="btnLoading" @click="save">
                        保存
                    </el-button>
                    <el-button size="small" @click="inShow = false"> 取消 </el-button>
                </div>
                <el-row :gutter="8">
                    <el-col :span="6">
                        <el-form-item label="提单号" prop="hblNo">
                            <el-input v-model="inFormData.hblNo" clearable> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="付款方式" prop="payment">
                            <selectDown
                                v-model:modelData="inFormData.payment"
                                placeholder="请选择"
                                urlType="dict"
                                urlQueryData="sys_payment">
                            </selectDown>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="业务编号" prop="doccode">
                            <el-input v-model="inFormData.doccode" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item
                            label="装货港"
                            prop="portDepartureName"
                            class="select-disabled">
                            <!-- <selectDown
                                v-model:modelData="inFormData.portDepartureId"
                                placeholder="请输入"
                                urlType="port"
                                :option="initOption.zhgOption"
                                :disabled="true">
                            </selectDown> -->
                            <el-input v-model="inFormData.portDepartureLabel" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="8">
                    <el-col :span="6">
                        <el-form-item
                            class="select-disabled"
                            label="中转港"
                            prop="portTransportName">
                            <el-input v-model="inFormData.portTransportLabel" disabled> </el-input>
                            <!-- <selectDown
                                v-model="inFormData.portTransportId"
                                placeholder="请输入"
                                urlType="port"
                                :disabled="true"
                                :option="initOption.zzgOption">
                            </selectDown> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item
                            label="目的港"
                            class="select-disabled"
                            prop="portDestinationName">
                            <el-input v-model="inFormData.portDestinationtLabel" disabled>
                            </el-input>
                            <!-- <selectDown
                                v-model="inFormData.portDestinationId"
                                placeholder="请输入"
                                urlType="port"
                                :option="initOption.mdgOption"
                                :disabled="true">
                            </selectDown> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="船名" prop="vessel">
                            <el-input v-model="inFormData.vessel" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="航次" prop="voyage">
                            <el-input v-model="inFormData.voyage" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="middle-box">
                    <span class="middle-choose-btn" @click="openBLDialog"> 选择收发货人 </span>
                </div>
                <el-row :gutter="8">
                    <el-col :span="12">
                        <el-form-item label="发货人">
                            <template #label="scope">
                                <el-button
                                    link
                                    @click="openBLHistoryDialog('发货人')"
                                    type="primary">
                                    {{ scope.label }}
                                </el-button>
                            </template>
                            <el-input v-model="inFormData.hblShipperMemo" type="textarea">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收货人">
                            <template #label="scope">
                                <el-button
                                    link
                                    @click="openBLHistoryDialog('收货人')"
                                    type="primary">
                                    {{ scope.label }}
                                </el-button>
                            </template>
                            <el-input v-model="inFormData.hblConsigneeMemo" type="textarea">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="8">
                    <el-col :span="12">
                        <el-form-item label="通知人">
                            <template #label="scope">
                                <el-button
                                    link
                                    @click="openBLHistoryDialog('通知人')"
                                    type="primary">
                                    {{ scope.label }}
                                </el-button>
                            </template>
                            <el-input v-model="inFormData.hblNotifyMemo" type="textarea">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="海外代理">
                            <template #label="scope">
                                <el-button
                                    link
                                    @click="openBLHistoryDialog('海外代理')"
                                    type="primary">
                                    {{ scope.label }}
                                </el-button>
                            </template>
                            <el-input v-model="inFormData.overseaAgentMemo" type="textarea">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="8">
                    <el-col :span="12">
                        <el-form-item label="第二通知人">
                            <template #label="scope">
                                <el-button
                                    link
                                    @click="openBLHistoryDialog('第二通知人')"
                                    type="primary">
                                    {{ scope.label }}
                                </el-button>
                            </template>
                            <el-input v-model="inFormData.hblSecondNotifyMemo" type="textarea">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="8">
                    <el-col :span="12">
                        <el-form-item label="唛头">
                            <el-input v-model="inFormData.marks" type="textarea" disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="品名描述">
                            <el-input
                                v-model="inFormData.cargoDescription"
                                type="textarea"
                                disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="8">
                    <el-col :span="6">
                        <el-form-item label="件数">
                            <el-input v-model="inFormData.digit" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="包装单位">
                            <selectDown
                                v-model:modelData="inFormData.packageUom"
                                placeholder="请选择"
                                urlType="package">
                            </selectDown>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="毛重">
                            <el-input v-model="inFormData.grossWeight" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="体积">
                            <el-input v-model="inFormData.volume" disabled> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div style="margin-bottom: 18px">
                    <el-button type="primary" @click="openBoxDialog"> 选择装箱信息 </el-button>
                    <el-button type="danger" @click="deleteData"> 删除 </el-button>
                </div>
                <el-table
                    :data="inFormData.detailList"
                    stripe
                    border
                    :cell-class-name="tableCellClassName"
                    size="small"
                    @cell-click="cellClick"
                    @selection-change="selectChange">
                    <el-table-column type="selection" width="50" />
                    <el-table-column label="箱号" prop="ctnNo"> </el-table-column>
                    <el-table-column label="品名" prop="cargoDescription">
                        <template #default="scope">
                            <div v-if="scope.row.index === rowIndex">
                                <el-input v-model="scope.row.cargoDescription" size="small">
                                </el-input>
                            </div>
                            <span v-else>
                                {{ scope.row.cargoDescription }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="HSCode" prop="hscode">
                        <template #default="scope">
                            <div v-if="scope.row.index === rowIndex">
                                <el-input v-model="scope.row.hscode" size="small"> </el-input>
                            </div>
                            <span v-else>
                                {{ scope.row.hscode }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="件数" prop="digit">
                        <template #default="scope">
                            <div v-if="scope.row.index === rowIndex">
                                <!-- <el-input-number
                                    v-model="scope.row.digit"
                                    controls-position="right"
                                    size="small"
                                  >
                                  </el-input-number> -->
                                <el-input
                                    v-model="scope.row.digit"
                                    size="small"
                                    @input="scope.row.digit = validateNumber(scope.row.digit)">
                                </el-input>
                            </div>
                            <span v-else>
                                {{ scope.row.digit }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="毛重" prop="grossWeight">
                        <template #default="scope">
                            <div v-if="scope.row.index === rowIndex">
                                <el-input-number
                                    v-model="scope.row.grossWeight"
                                    controls-position="right"
                                    size="small">
                                </el-input-number>
                            </div>
                            <span v-else>
                                {{ scope.row.grossWeight }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="体积" prop="volume">
                        <template #default="scope">
                            <div v-if="scope.row.index === rowIndex">
                                <el-input-number
                                    v-model="scope.row.volume"
                                    controls-position="right"
                                    size="small">
                                </el-input-number>
                            </div>
                            <span v-else>
                                {{ scope.row.volume }}
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </el-dialog>
        <docDetailBaseBLDialog ref="BLDialog" @choose="getBLTitle"> </docDetailBaseBLDialog>
        <docDetailBaseBLHistoryDialog
            ref="BLHistoryDialog"
            :inKey="inkey"
            @choose="getBLHistoryTitle">
        </docDetailBaseBLHistoryDialog>
        <el-dialog v-model="boxDialog.show" title="数据选取" append-to-body>
            <el-button type="primary" size="small" @click="chooseBox" style="margin-bottom: 8px">
                选取数据
            </el-button>
            <el-table
                :data="allData.docWorkCtnList"
                border
                size="small"
                ref="tableBoxSelectRef"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50" />
                <el-table-column label="箱号" prop="ctnNo" />
                <el-table-column label="箱型" prop="containerCode" />
                <el-table-column label="件数" prop="digit" />
                <el-table-column label="毛重" prop="grossWeight" />
                <el-table-column label="体积" prop="volume" />
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { defineComponent, toRaw } from 'vue'
import selectDown from './selectDown.vue'
import docDetailBaseBLDialog from './docDetailBaseBLDialog.vue'
import docDetailBaseBLHistoryDialog from './docDetailBaseBLHistoryDialog.vue'
import { mergeAndRemoveDuplicates } from '@/public/publicUtils'
import { validateOnlyNumberTwo, validateNumber } from '@/utils/validate.js'
export default defineComponent({
    components: {
        selectDown,
        docDetailBaseBLDialog,
        docDetailBaseBLHistoryDialog,
    },
    inject: ['hBillBoxCopy'],
    props: {
        show: {
            type: Boolean,
            default: false,
        },
        allData: {
            type: Object,
            default: () => {},
        },
        formData: {
            type: Object,
            default: () => {},
        },
        loading: {
            type: Boolean,
            default: false,
        },
        //初始化option
        initOption: {
            type: Object,
            default: () => {},
        },
    },
    emits: ['update:show', 'saveSuccess'],
    computed: {
        inShow: {
            get() {
                return this.show
            },
            set(value) {
                this.$emit('update:show', value)
            },
        },
    },
    data() {
        return {
            rowIndex: -1, //行索引
            columnIndex: -1, //列索引
            selectData: [], //选中的数据
            inFormData: {},
            formRules: {
                hblNo: [
                    {
                        required: true,
                        message: '提单号不能为空',
                        trigger: 'change',
                    },
                ],
                payment: [
                    {
                        required: true,
                        message: '付款方式不能为空',
                        trigger: 'change',
                    },
                ],
            },
            btnLoading: false,
            inkey: 0,
            boxDialog: {
                show: false,
                tableSelect: [],
            },
        }
    },
    methods: {
        validateNumber,
        /**
         * 选择后的数据
         * @param {Array} selection - 当前选中的数据
         */
        selectChange(selection) {
            let arr = []
            for (let item of selection) {
                let ret = toRaw(item)
                if (ret !== undefined) {
                    arr.push(ret)
                }
            }
            this.selectData = arr
        },
        tableCellClassName({ row, column, rowIndex, columnIndex }) {
            column.index = columnIndex
            row.index = rowIndex
        },
        //单元格被点击时会触发该事件
        cellClick(row, column, cell, event) {
            this.rowIndex = row.index
            this.columnIndex = column.index
        },
        openBLDialog() {
            if (this.allData.custId) {
                this.$refs.BLDialog.open(this.allData.custId)
            } else {
                this.$message.error('请选择委托单位')
            }
        },
        /**
         * 选择收发货人选取
         * @param {object} bldata - 组件选取数据
         */
        getBLTitle(bldata) {
            this.inFormData.hblShipperMemo = bldata.shiperTitle
            this.inFormData.hblConsigneeMemo = bldata.receiverTitle
            this.inFormData.hblNotifyMemo = bldata.notifyTitle
        },
        openBLHistoryDialog(strKey) {
            if (this.allData.custId) {
                switch (strKey) {
                    case '发货人':
                        this.inkey = 1
                        break
                    case '收货人':
                        this.inkey = 2
                        break
                    case '通知人':
                        this.inkey = 3
                        break
                    case '第二通知人':
                        this.inkey = 5
                        break
                    case '海外代理':
                        this.inkey = 4
                        break
                    default:
                        break
                }

                this.$refs.BLHistoryDialog.open(this.allData.custId)
            } else {
                this.$message.error('请在基本信息中选择委托单位')
            }
        },
        /**
         * 单独选取
         * @param {object} blHistorydata - 组件选取数据
         */
        getBLHistoryTitle(blHistorydata) {
            let strKey = this.inkey
            switch (strKey) {
                case 1:
                    this.inFormData.hblShipperMemo = blHistorydata
                    break
                case 2:
                    this.inFormData.hblConsigneeMemo = blHistorydata
                    break
                case 3:
                    this.inFormData.hblNotifyMemo = blHistorydata
                    break
                case 5:
                    this.inFormData.hblSecondNotifyMemo = blHistorydata
                    break
                case 4:
                    this.inFormData.overseaAgentMemo = blHistorydata
                    break
                default:
                    break
            }
        },
        /**
         * 保存
         */
        save() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.btnLoading = true
                    // 复制修改内容并删除自定义添加的内容用于显示的港口信息
                    let inFormData = JSON.parse(JSON.stringify(this.inFormData))
                    delete inFormData.portDepartureLabel
                    delete inFormData.portTransportLabel
                    delete inFormData.portDestinationtLabel
                    this.$http
                        .post('/api/docworkhbill/SaveBill', inFormData)
                        .then((res) => {
                            if (res.status) {
                                this.inShow = false
                                this.$emit('saveSuccess', res.data)
                                this.$message.success(res.message)
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                        .finally(() => (this.btnLoading = false))
                }
            })
        },
        /**
         * 打开选择箱子弹窗
         */
        openBoxDialog() {
            let docWorkCtnListCopy = JSON.parse(JSON.stringify(this.allData.docWorkCtnList))
            docWorkCtnListCopy.forEach((item) => {
                delete item.index
            })
            console.log(
                this.allData.docWorkCtnList,
                this.hBillBoxCopy,
                '----------',
                docWorkCtnListCopy,
                JSON.stringify(this.allData.docWorkCtnList) === JSON.stringify(this.hBillBoxCopy)
            )
            // console.log(this.hBillBoxCopy)
            if (JSON.stringify(docWorkCtnListCopy) === JSON.stringify(this.hBillBoxCopy)) {
                this.boxDialog.show = true
            } else {
                this.$message.warning('请先保存装箱信息！')
            }
        },
        handleSelectionChange(selection) {
            this.boxDialog.tableSelect = selection
        },
        /**
         * 选取数据
         */
        chooseBox() {
            let selectArr = []
            this.boxDialog.tableSelect.forEach((t) => {
                const newData = {
                    hbillId: this.inFormData.id || 0,
                    ctnId: t.id,
                    digit: t.digit,
                    packageUom: '',
                    grossWeight: t.grossWeight,
                    volume: t.volume,
                    cargoDescription: '',
                    hscode: '',
                    ctnNo: t.ctnNo,
                }
                selectArr.push(newData)
                // this.inFormData.detailList.push(newData);
            })
            this.inFormData.detailList = mergeAndRemoveDuplicates(
                JSON.parse(JSON.stringify(this.inFormData.detailList)),
                selectArr,
                'ctnId'
            )
            this.$refs.tableBoxSelectRef.clearSelection()
            this.boxDialog.show = false
        },
        /**
         * 删除装箱信息
         */
        deleteData() {
            if (this.selectData.length > 0) {
                let newArray = []
                this.inFormData.detailList.forEach((item) => {
                    if (!this.selectData.find((t) => t == item)) {
                        newArray.push(item)
                    }
                })
                this.inFormData.detailList = newArray
            } else {
                this.$message.warning('请先选择')
            }
        },
    },
    watch: {
        inShow(newVal) {
            if (newVal) {
                this.inFormData = this.formData
            } else {
                this.inFormData = {
                    id: null,
                    custId: null,
                    cargoDescription: null, //品名描述
                    digit: null, //件数
                    docId: null,
                    grossWeight: null, //毛重
                    hblNo: null, //提单号
                    hblSecondNotifyMemo: null, //货代提单-第二通知人详细信息
                    hblConsigneeMemo: null, //货代提单-收货人详细信息
                    hblNotifyMemo: null, //货代提单-通知人详细信息
                    hblShipperMemo: null, //货代提单-发货人详细信息
                    marks: null, //数据只为显示 唛头
                    overseaAgentMemo: null, //海外代理详细信息
                    packageUom: null, //单位
                    payment: null, //付款方式
                    volume: null, //体积
                    portDepartureId: null, //数据只为显示 装货港
                    portDepartureName: null, //数据只为显示
                    portTransportId: null, //数据只为显示 中转港
                    portTransportName: null, //数据只为显示
                    portDestinationId: null, //数据只为显示 目的港
                    portDestinationName: null, //数据只为显示
                    vessel: null, //数据只为显示 船名
                    voyage: null, //数据只为显示 航次
                    detailList: [],
                    docWorkCtnList: [],
                    docVersion: null,
                }
            }
            this.$nextTick(() => {
                this.$refs.form.clearValidate()
            })
        },
        'inFormData.detailList': {
            handler(newVal) {
                let allDigit = 0
                let allGrossWeight = 0
                let allVolume = 0
                let allCargoDescription = ''
                newVal.forEach((t) => {
                    allDigit = allDigit + (t.digit ? parseInt(t.digit) : 0)
                    allGrossWeight = allGrossWeight + t.grossWeight
                    allVolume = allVolume + t.volume
                    if (t.cargoDescription) {
                        allCargoDescription += t.cargoDescription + '\n'
                    }
                })

                this.inFormData.cargoDescription = allCargoDescription
                this.inFormData.digit = allDigit
                this.inFormData.grossWeight = allGrossWeight
                this.inFormData.volume = allVolume
            },
            deep: true,
        },
    },
    mounted() {},
})
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
    height: 800px;
    overflow-y: auto;
    overflow-x: hidden;
}
:deep(.el-form) {
    .el-form-item__label {
        font-size: 12px;
    }

    .select-disabled {
        .el-select__selection span {
            color: #a8abb2;
        }
    }
}

:deep(.el-table) {
    .el-table__header-wrapper th {
        background-color: #f7f8fa !important;
    }

    .el-input-number {
        .el-input-number__decrease {
            display: none;
        }

        .el-input-number__increase {
            display: none;
        }

        .el-input__inner {
            // padding: 0 15px;
            text-align: left;
        }
    }

    .el-input-number.is-controls-right .el-input__wrapper {
        padding: 1px 7px;
    }
    .el-input-number--small {
        width: 100%;
    }
}

.middle-box {
    margin-bottom: 18px;

    .middle-choose-btn {
        cursor: pointer;
        color: #0063b9;
    }
}
</style>
